<div class="flex flex-col gpt-back-top-btn" >
  <button id="backtop_btn" class="animate-duration-100 rounded-md p-2.5 transition-colors hover:bg-$c-fg-5">
    <svg xmlns="http://www.w3.org/2000/svg" width="1.2em" height="1.2em" viewBox="0 0 32 32"><path fill="currentColor" d="M16 4L6 14l1.41 1.41L15 7.83V28h2V7.83l7.59 7.58L26 14L16 4z" /></svg>
  </button>
  <button id="backbottom_btn" class="rotate-180 animate-duration-100 rounded-md p-2.5 transition-colors hover:bg-$c-fg-5">
    <svg xmlns="http://www.w3.org/2000/svg" width="1.2em" height="1.2em" viewBox="0 0 32 32"><path fill="currentColor" d="M16 4L6 14l1.41 1.41L15 7.83V28h2V7.83l7.59 7.58L26 14L16 4z" /></svg>
  </button>
</div>
<script>
import { trackEvent } from '../utils/track'

const backtop_btn = document.getElementById('backtop_btn') as HTMLElement
const backbottom_btn = document.getElementById('backbottom_btn') as HTMLElement
backtop_btn.style.display = 'none'
backbottom_btn.style.display = 'none'

function handleMove() {
  const backtop_btn = document.getElementById('backtop_btn') as HTMLElement
  const backbottom_btn = document.getElementById('backbottom_btn') as HTMLElement

  if (window.scrollY > 100) backtop_btn.style.display = 'block'
  else backtop_btn.style.display = 'none'

  const scrollTop = document.documentElement.scrollTop
  const clientHeight = document.documentElement.clientHeight
  const scrollHeight = document.documentElement.scrollHeight

  if (scrollTop + clientHeight >= scrollHeight - 100) backbottom_btn.style.display = 'none'
  else backbottom_btn.style.display = 'block'
}

window.addEventListener('scroll', handleMove)
window.addEventListener('resize', handleMove)
const observer = new MutationObserver(handleMove)
observer.observe(document.querySelector('astro-island[data-solid-render-id] > main')!, { childList: true, subtree: true })

backbottom_btn.onclick = () => {
  const scrollHeight = document.documentElement.scrollHeight
  window.scrollTo({ top: scrollHeight, behavior: 'smooth' })
  trackEvent('backbottom')
}
backtop_btn.onclick = () => {
  window.scrollTo({ top: 0, behavior: 'smooth' })
  trackEvent('backtop')
}

window.addEventListener('keydown', (event) => {
  if (event.code === 'PageUp') backtop_btn.click()
  else if (event.code === 'PageDown') backbottom_btn.click()
  else return
  event.preventDefault()
})
</script>
